import * as ActionTypes from './type'
import router from '@/router'

import * as Functions from '@/core/functions.js'

export default {
  [ActionTypes.MENU_CHANGE]: (state, data) => {
    // 菜单的索引
    let index = data.index
    // 首先改变menu的显示
    state.menu = null
    let menu = { index: index }
    state.menu = menu

    // 通过 menu、index 找到对应的 path
    let menuItem = Functions.getMenuItemByIndex(index)
    if (!menuItem) {
      return
    }
    let currentPath = state.nav.index
    let list = JSON.parse(JSON.stringify(state.nav.list))
    let nav
    if (Functions.pathIsExistInNavList(list, menuItem.path)) {
      nav = { index: menuItem.path, list: list }
    } else {
      if (list.length > 9) {
        list.splice(1, 1)
      }
      list.push({
        menuIndex: menuItem.index,
        name: menuItem.name,
        path: menuItem.path
      })
      nav = { index: menuItem.path, list: list }
    }

    state.nav = null
    state.nav = nav

    // console.log('currentPath', currentPath)
    if (data.isAlwaysPush) {
      router.push(menuItem.path)
    } else if (currentPath !== menuItem.path) {
      // 跳转
      router.push(menuItem.path)
    }
  },
  [ActionTypes.MENU_INIT]: (state, data) => {
    // 菜单的索引
    let menuIndex = data.menu.index ? data.menu.index : '1'
    let list = Functions.getInitList(state.nav.list)

    // 先改变菜单状态
    state.menu = null
    let menu = { index: menuIndex }
    state.menu = menu

    // 判断 list 当中是否存在，如果不存在则直接添加
    let nav
    if (Functions.pathIsExistInNavList(list, data.fullPath)) {
      nav = { index: data.fullPath, list: list }
    } else {
      list.push({
        menuIndex: menuIndex,
        name: Functions.getNavNameByPath(data.menu, data.fullPath),
        path: data.fullPath
      })
      nav = { index: data.fullPath, list: list }
    }
    state.nav = null
    state.nav = nav
  }
}
